<template>
	<xn-form-container
		:title="workExperienceData.length > 0 ? '工作经历详情' : '暂无工作经历'"
		:width="700"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<div v-if="workExperienceData.length > 0">
			<a-card
				v-for="(work, index) in workExperienceData"
				:key="index"
				:title="work.company || '未命名公司'"
				style="margin-bottom: 16px"
			>
				<a-descriptions :column="1" bordered>
					<a-descriptions-item label="职位">
						{{ work.position || '未填写' }}
					</a-descriptions-item>
					<a-descriptions-item label="工作时间">
						{{ formatWorkPeriod(work.startDate, work.endDate) }}
					</a-descriptions-item>
					<a-descriptions-item label="离职原因">
						{{ work.reasonForLeaving || '未填写' }}
					</a-descriptions-item>
					<a-descriptions-item label="证明人联系方式">
						{{ work.reference || '未填写' }}
					</a-descriptions-item>
				</a-descriptions>
			</a-card>
		</div>
		<a-empty v-else description="暂无工作经历信息" />

		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { message } from 'ant-design-vue'
	import dayjs from 'dayjs'

	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })

	// 工作经历数据
	const workExperienceData = ref([])

	// 格式化工作时间
	const formatWorkPeriod = (startDate, endDate) => {
		if (!startDate && !endDate) return '未填写'
		const start = startDate ? dayjs(startDate).format('YYYY-MM') : '未填写'
		const end = endDate ? dayjs(endDate).format('YYYY-MM') : '至今'
		return `${start} 至 ${end}`
	}

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			try {
				// 解析工作经历JSON字符串
				if (record.workExperience) {
					const workData =
						typeof record.workExperience === 'string' ? JSON.parse(record.workExperience) : record.workExperience

					workExperienceData.value = Array.isArray(workData) ? workData : []
				} else {
					workExperienceData.value = []
				}
			} catch (e) {
				console.error('解析工作经历数据失败:', e)
				workExperienceData.value = []
				message.error('工作经历数据解析失败')
			}
		} else {
			workExperienceData.value = []
		}
	}

	// 关闭抽屉
	const onClose = () => {
		workExperienceData.value = []
		visible.value = false
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
